/**
 * Copyright (C) 2021 - 2031 O-Cubes Co., Ltd.
 */

/****************************************************************
 *  @file    spi_flash_test.c
 *  @brief   SPI/QSPI Flash testcase source file
 *  @version v1.0
 *  @date    03. Apr. 2023
 ****************************************************************/

#include "hal_api.h"
#include "printf.h"

#define SPIFLASH_TEST_BUFFER_SIZE 1024

static uint8_t spiflash_test_buf[SPIFLASH_TEST_BUFFER_SIZE];

int32_t test_spi_flash(void)
{
	uint32_t i = 0;
	uint32_t j = 0;
	int32_t result = 0;
	uint32_t addr = 0;
	uint32_t size = SPIFLASH_TEST_BUFFER_SIZE;

	printf("\r\n[SPIFLASH]: TEST START\r\n");


	for (i = 0; i < 3; i++) {
		addr = 260*1024 + i * 1024;

		for (j = 0; j < size; j++) {
			spiflash_test_buf[j] = j/128 + j%128;
		}

		result = Hal_Flash_Erase(addr, size);

		if (result == 0) {
			printf("Erase flash data success. Addr[0x%08lX], Size[%lu].\r\n", addr, size);
		} else {
			printf("Erase flash data failed.\r\n");
			continue;
		}

		result = Hal_Flash_Write(addr, size, spiflash_test_buf);

		if (result == 0) {
			printf("Write flash data success. Addr[0x%08lX], Size[%lu].\r\n", addr, size);
		} else {
			printf("Write flash data failed.\r\n");
			continue;
		}

		result = Hal_Flash_Read(addr, size, spiflash_test_buf);

		if (result == 0) {
			printf("Read flash data success. Addr[0x%08lX], Size[%lu].\r\n", addr, size);
		} else {
			printf("Read flash data failed.\r\n");
			continue;
		}

		for (j = 0; j < size; j++) {
			if (spiflash_test_buf[j] != j/128 + j%128) {
				printf("Flash data check error, test failed. Addr[0x%08lX] = 0x%02x.\r\n",
					addr + j, spiflash_test_buf[j]);
				break;
			}
		}

		if (j == size) {
			printf("The flash test result is success, Addr[0x%08lX], Size[%lu].\r\n", addr, size);
		}

	}

	printf("[SPIFLASH]: TEST END\r\n");

	return 0;
}
